# Python 图像分割代码：
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('camera.png', cv2.IMREAD_GRAYSCALE)
# 固定阈值分割 T=100
_, out1 = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)
# 迭代阈值分割
T = img.mean()
done=False
while not done:
    t0 = img[img < T].mean()
    t1 = img[img >= T].mean()
    t = (t0 + t1) / 2
    done = abs(T - t) < 1
    T = t
_, img_iter = cv2.threshold(img, T, 255, cv2.THRESH_BINARY)
plt.subplot(1,3,1), plt.imshow(img,cmap='gray'), plt.title('original'), plt.axis('off')
plt.subplot(1,3,2), plt.imshow(out1,cmap='gray'), plt.title('fixed'), plt.axis('off')
plt.subplot(1,3,3), plt.imshow(img_iter,cmap='gray'), plt.title('iter'), plt.axis('off')
plt.show()
